package com.learning.spring.security.basic.authentication.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

import static org.springframework.security.config.Customizer.withDefaults;

/**
 * ClassName: SecurityConfig
 * Description: Basic Authentication 基本认证
 * Date: 2022/7/29 9:48
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@Configuration
public class SecurityConfig {


    /**
     * 1. 未认证请求处理流程
     * - FilterSecurityInterceptor 抛出 AccessDeniedException
     * - ExceptionTranslationFilter 交给 BasicAuthenticationEntryPoint
     *      - 发送响应头  WWW-Authenticate: Basic realm="Realm"
     *      - 响应数据 401 Unauthorized
     * - 浏览器访问，弹框输入账号密码
     *
     * 2. 账户密码请求处理流程
     * - 数据的账号密码会以 username:pwd 的格式进行 Base64 编码
     * - 在请求头中会把编码过的账户密码以这样的形式进行发送 Authorization: Basic dXNlcjoxMjM0NTY=
     * - BasicAuthenticationFilter 拦截请求，创建 UsernamePasswordAuthenticationToken 进行验证
     *
     * */


    /**
     * Basic Authentication 自定义配置
     *
     * @param http
     * @return
     * @throws Exception
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated();
        http.httpBasic(withDefaults());
        return http.build();
    }
}
